import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // progress bar style
// import api from '@/api'
const _import = require('./_import_' + process.env.NODE_ENV) // 引入获取组件的方法

Vue.use(VueRouter)

import Layout from '@/layout'
import EmptyLayout from '@/layout/empty'

const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login'),
    meta: {
      title: '登录'
    }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      name: 'dashboard',
      component: () => import('@/views/index'),
      meta: {
        title: store.state.settings.dashboardTitle
      }
    },
    {
      path: 'personal',
      component: EmptyLayout,
      redirect: '/personal/setting',
      meta: {
        title: '个人中心',
        breadcrumb: false
      },
      children: [{
        path: 'setting',
        name: 'personalSetting',
        component: () => import('@/views/personal/setting'),
        meta: {
          title: '个人设置'
        }
      },
      {
        path: 'edit/password',
        name: 'personalEditPassword',
        component: () =>
          import('@/views/personal/edit.password'),
        meta: {
          title: '修改密码'
        }
      }
      ]
    },
    {
      path: 'reload',
      name: 'reload',
      component: () => import('@/views/reload')
    }
    ]
  },
]

let asyncRoutes = [{
  meta: {
    title: '演示',
    icon: 'sidebar-default'
  },
  children: [
    // 账号管理
    {
      // 路由路径
      path: '/control',
      // 重定向路径
      redirect: '/control/index',
      // 组件
      component: Layout,
      // 标题和图标
      meta: {
        title: '账号管理',
        icon: 'sidebar-component',
      },
      // 子路由
      children: [
        {
          // 路由路径
          path: 'index',
          // 路由名称
          name: 'controlIndex',
          // 组件
          component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/Admin'),
          // 标题、是否显示侧边栏、是否显示面包屑、激活的菜单
          meta: {
            title: '账号管理',
            sidebar: false,
            breadcrumb: false,
            activeMenu: '/control'
          }
        }
      ]
    },


    // 商品管理1
    {
      path: '/productsManage',
      redirect: '/productsManage/index',
      component: Layout,
      meta: {
        title: '商品管理',
        icon: 'sidebar-default',
      },
      children: [
        {
          path: 'index',
          name: 'productsManageIndex',
          component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/ProductsManage'),
          meta: {
            title: '商品管理',
            sidebar: false,
            breadcrumb: false,
            activeMenu: '/productsManage'
          }
        }
      ]
    },

    // 商品分类管理1
    {
      path: '/classes',
      redirect: '/classes/index',
      component: Layout,
      meta: {
        title: '商品分类管理',
        icon: 'sidebar-mock',
      },
      children: [
        {
          path: 'index',
          name: 'classesIndex',
          component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/Classes'),
          meta: {
            title: '商品分类管理',
            sidebar: false,
            breadcrumb: false,
            activeMenu: '/classes'
          }
        }
      ]
    },

    // 优惠券管理1
    {
      path: '/couponsManage',
      redirect: '/couponsManage/index',
      component: Layout,
      meta: {
        title: '优惠券管理',
        icon: 'sidebar-mock',
      },
      children: [
        {
          path: 'index',
          name: 'couponsManageIndex',
          component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/CouponsManage'),
          meta: {
            title: '优惠券',
            sidebar: false,
            breadcrumb: false,
            activeMenu: '/couponsManage'
          }
        }
      ]
    },

    // 订单管理1
    {
      path: '/ordersManage',
      redirect: '/ordersManage/index',
      component: Layout,
      meta: {
        title: '订单管理',
        icon: 'sidebar-mock',
      },
      children: [
        {
          path: 'index',
          name: 'ordersManageIndex',
          component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/OrdersManage'),
          meta: {
            title: '订单管理',
            sidebar: false,
            breadcrumb: false,
            activeMenu: '/ordersManage'
          }
        }
      ]
    },

    //购物车管理1
    // {
    //   path: '/shoppingcartsManage',
    //   redirect: '/shoppingcartsManage/index',
    //   component: Layout,
    //   meta: {
    //     title: '购物车管理1',
    //     icon: 'sidebar-mock',
    //   },
    //   children: [
    //     {
    //       path: 'index',
    //       name: 'shoppingcartsManageIndex',
    //       component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/ShoppingcartsManage'),
    //       meta: {
    //         title: '购物车管理',
    //         sidebar: false,
    //         breadcrumb: false,
    //         activeMenu: '/shoppingcartsManage'
    //       }
    //     }
    //   ]
    // },

    //轮播图管理1
    {
      path: '/carouselsManage',
      redirect: '/carouselsManage/index',
      component: Layout,
      meta: {
        title: '轮播图管理',
        icon: 'sidebar-mock',
      },
      children: [
        {
          path: 'index',
          name: 'carouselsManageIndex',
          component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/CarouselsManage'),
          meta: {
            title: '轮播图管理',
            sidebar: false,
            breadcrumb: false,
            activeMenu: '/carouselsManage'
          }
        }
      ]
    },

    //活动管理1
    {
      path: '/activitysManage',
      redirect: '/activitysManage/index',
      component: Layout,
      meta: {
        title: '活动管理',
        icon: 'sidebar-mock',
      },
      children: [
        {
          path: 'index',
          name: 'activitysManageIndex',
          component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/ActivitysManage'),
          meta: {
            title: '活动管理',
            sidebar: false,
            breadcrumb: false,
            activeMenu: '/activitysManage'
          }
        }
      ]
    },

    // 商品分类
    // {
    //   path: '/productClass',
    //   redirect: '/productClass/index',
    //   component: Layout,
    //   meta: {
    //     title: '商品分类',
    //     icon: 'sidebar-menu',
    //   },
    //   children: [
    //     {
    //       path: 'index',
    //       name: 'productClassIndex',
    //       component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/ProductClass'),
    //       meta: {
    //         title: '商品分类',
    //         sidebar: false,
    //         breadcrumb: false,
    //         activeMenu: '/productClass'
    //       }
    //     }
    //   ]
    // },

    // 商品管理
    // {
    //   path: '/productManage',
    //   redirect: '/productManage/index',
    //   component: Layout,
    //   meta: {
    //     title: '商品管理',
    //     icon: 'sidebar-default',
    //   },
    //   children: [
    //     {
    //       path: 'index',
    //       name: 'productManageIndex',
    //       component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/ProductManage'),
    //       meta: {
    //         title: '商品管理',
    //         sidebar: false,
    //         breadcrumb: false,
    //         activeMenu: '/productManage'
    //       }
    //     }
    //   ]
    // },

    // 优惠券
    // {
    //   path: '/jpgRresource',
    //   redirect: '/jpgRresource/index',
    //   component: Layout,
    //   meta: {
    //     title: '优惠券',
    //     icon: 'sidebar-mock',
    //   },
    //   children: [
    //     {
    //       path: 'index',
    //       name: 'jpgRresourceIndex',
    //       component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/JPGResource'),
    //       meta: {
    //         title: '优惠券',
    //         sidebar: false,
    //         breadcrumb: false,
    //         activeMenu: '/jpgRresource'
    //       }
    //     }
    //   ]
    // },

    // // PDF资源
    // {
    //   path: '/pdfResource',
    //   redirect: '/pdfResource/index',
    //   component: Layout,
    //   meta: {
    //     title: 'PDF资源',
    //     icon: 'sidebar-mock',
    //   },
    //   children: [
    //     {
    //       path: 'index',
    //       name: 'pdfResourceIndex',
    //       component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/PDFResource'),
    //       meta: {
    //         title: 'PDF资源',
    //         sidebar: false,
    //         breadcrumb: false,
    //         activeMenu: '/pdfResource'
    //       }
    //     }
    //   ]
    // },







    // // 视频资源
    // {
    //   path: '/mp4Rresource',
    //   redirect: '/mp4Rresource/index',
    //   component: Layout,
    //   meta: {
    //     title: '视频资源',
    //     icon: 'sidebar-mock',
    //   },
    //   children: [
    //     {
    //       path: 'index',
    //       name: 'mp4RresourceIndex',
    //       component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/MP4Resource'),
    //       meta: {
    //         title: '视频资源',
    //         sidebar: false,
    //         breadcrumb: false,
    //         activeMenu: '/mp4Rresource'
    //       }
    //     }
    //   ]
    // },

    // 系统日志
    // {
    //   path: '/journal',
    //   redirect: '/journal/index',
    //   component: Layout,
    //   meta: {
    //     title: '系统日志',
    //     icon: 'sidebar-permission',
    //   },
    //   children: [
    //     {
    //       path: 'index',
    //       name: 'journalIndex',
    //       component: () => import(/* webpackChunkName: 'mock_example' */ '@/views/Journal'),
    //       meta: {
    //         title: '系统日志',
    //         sidebar: false,
    //         breadcrumb: false,
    //         activeMenu: '/journal'
    //       }
    //     }
    //   ]
    // },

  ]
}]

const lastRoute = [{
  path: '*',
  component: () => import('@/views/404'),
  meta: {
    title: '404',
    sidebar: false
  }
}]

const router = new VueRouter({
  routes: constantRoutes
})

// 解决路由在 push/replace 了相同地址报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}

router.beforeEach(async (to, from, next) => {

  // 如果跳转到dashboard页面，则跳转到控制台页面
  if (to.name == 'dashboard') {
    next({
      path: '/control/index',
      replace: true
    })
    return
  }
  // 如果启用进度条，则开始进度条
  store.state.settings.enableProgress && NProgress.start();
  // 已经登录，但还没根据权限动态挂载路由

  if (store.getters['user/isLogin'] && !store.state.menu.isGenerate) {
    // 判断是否登录，以及菜单是否已经生成
    router.matcher = new VueRouter({
      // 设置路由
      routes: constantRoutes
    }).matcher;
    const accessRoutes = await store.dispatch('menu/generateRoutes', {
      asyncRoutes,
      currentPath: to.path
    })
    accessRoutes.push(...lastRoute)

    accessRoutes.forEach(route => {
      router.addRoute(route)
    })
    next({ ...to, replace: true });
  }

  if (store.state.menu.isGenerate) {
    store.commit('menu/setHeaderActived', to.path)
  }
  to.meta.title && store.commit('settings/setTitle', to.meta.title)

  if (store.getters['user/isLogin']) {
    if (to.name) {
      if (to.matched.length !== 0) {
        // 如果已登录状态下，进入登录页会强制跳转到控制台页面
        if (to.name == 'login') {
          next({
            path: '/control/index',
            replace: true
          })
        } else if (!store.state.settings.enableDashboard && to.name == 'dashboard') {
          // 如果未开启控制台页面，则默认进入侧边栏导航第一个模块，但如果侧边栏导航没有模块，则还是进入控制台页面
          if (store.getters['menu/sidebarRoutes'].length > 0) {
            next({
              name: store.getters['menu/sidebarRoutes'][0].name,
              replace: true
            })
          }
        }
      } else {
        // 如果是通过 name 跳转，并且 name 对应的路由没有权限时，需要做这步处理，手动指向到 404 页面
        next({
          path: '/404'
        })
      }
    }
  } else {
    if (to.name != 'login') {
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  }
  next();
})

router.afterEach(() => {
  store.state.settings.enableProgress && NProgress.done()
})

export default router
